package com.sbm.shiro;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionContext;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import com.alibaba.fastjson.JSON;

public class ShiroSessionManager extends DefaultWebSessionManager {
	public static final Map<String, Serializable> cache = new HashMap<String, Serializable>();
	private static final Integer sessionCookieAge = 30 * 60;
	private static final Integer sessionAge = 30 * 60 * 1000;

	@Override
	protected void onStart(Session session, SessionContext context) {
		if (WebUtils.isHttp(context)) {
			HttpServletRequest request = WebUtils.getHttpRequest(context);
			HttpServletResponse response = WebUtils.getHttpResponse(context);
			request.removeAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_IS_NEW, true);
			String sessionId = UUID.randomUUID().toString().trim();
			Serializable id = session.getId();
			setSessionCookie(response, sessionId, sessionCookieAge);
			session.setTimeout(sessionAge);
			cache.put(sessionId, id);
		}
	}

	@Override
	protected Serializable getSessionId(ServletRequest servletRequest, ServletResponse servletResponse) {
		Serializable id = null;
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String sessionId = null;
		if (request.getCookies() != null)
			for (Cookie cookie : request.getCookies())
				if (cookie.getName().equals("JSESSIONID"))
					sessionId = cookie.getValue();
		if (sessionId == null || sessionId.isEmpty())
			sessionId = request.getParameter("access_token");
		System.out.println(JSON.toJSONString(request.getSession().getId()));
		if (sessionId != null && !sessionId.isEmpty())
			setSessionCookie(response, sessionId, sessionCookieAge);
		if (cache.containsKey(sessionId))
			id = cache.get(sessionId);
		return id;
	}

	private void setSessionCookie(HttpServletResponse response, String sessionId, Integer age) {
		Cookie cookie = new Cookie("JSESSIONID", sessionId);
		cookie.setHttpOnly(true);
		cookie.setPath("/");
		cookie.setMaxAge(age);
		response.addCookie(cookie);
	}
}
